//
//  OAuthViewController.swift
//  weibo
//
//  Created by 王、小胜 on 16/7/26.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
///用户登录控制器
class OAuthViewController: UIViewController {
    
    //懒加载webView
    private lazy var webView = UIWebView()
    
    //自动填充密码
    //web注入，以代码方式向web界面添加内容
    @objc private func autoFill(){
       
        let js = "document.getElementById('userId').value = '15736882323';" + "document.getElementById('passwd').value = 'wzs940211';"
        
        //让webview加载js
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    //MARK - 监听方法
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK - 设置界面
    override func loadView() {
        view = webView
        
        //设置代理
        webView.delegate = self
        
        //设置导航栏
        title = "登陆我的微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //加载页面
        self.webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))

      
   }
}



//MARK - Webview 代理方法


extension OAuthViewController:UIWebViewDelegate {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //1.判断访问的主机地址是否是百度
        guard let url = request.URL where url.host == "www.baidu.com" else {
            return true
        }
        
        //2.从百度地址的url 抽取‘code = ’是否存在
        guard let query = url.query where query.hasPrefix("code=") else{
            print("取消授权")
            
            return false
        }
        
        //3.从query 字符中抽取“code=” 后面的授权码
        let code = query.substringFromIndex("code=".endIndex)
        
        print(query)
        print("授权码是" + code)
        
        //4.加载accessToken
        
        UserAccountViewModel.sharedUserAccount.loadAccessToken(code) { (isSuccessed) -> () in
            if isSuccessed {
                print("成功了")
                
                print(UserAccountViewModel.sharedUserAccount.account)
            } else {
                print("失败了")
            }
        }
        return false
    }
    
}
